package edu.stthomas.seis752.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import edu.stthomas.seis752.model.Collection;
import edu.stthomas.seis752.model.CollectionType;
import edu.stthomas.seis752.model.Member;
import edu.stthomas.seis752.model.User;

@Repository
public class UserDaoImpl implements UserDao {

	// EntityManager is used instead of Hibernate SessionManager to get the application to work on app engine
	@PersistenceContext
	private EntityManager manager;

	
	@Override
	public CollectionType getCollectionType(String code) {
		return (CollectionType)manager.getReference(CollectionType.class, code);
	}

	@Override
	public Collection addCollection(Collection coll) {
		manager.persist(coll);
		return coll;
	}

	public void saveCollection(Collection coll){
		manager.persist(coll);
	}
	
	public void saveMember(Member m){
		manager.persist(m);
	}
	
	public void remove(Object o){
		manager.remove(o);
	}
	
	public Object getPersistedObject(Class c, Object id){
		return manager.getReference(c, id);
	}
	
	public List<Collection> getCollectionsForOwner(Long ownerId) {
		Query  query = manager.createQuery("FROM Collection where ownerId =:ownerId");
		query.setParameter("ownerId", ownerId);
		// this is not ideal but just a test for now
		List<Collection> colls = (List<Collection>) query.getResultList();
		return colls;
	}
	
	public void addUser(User user) {
		// this is how you would save the user
		manager.persist(user);
	}

	// this is how you would get User using new EntityManger
	public User getUser(Long id) {
		Query  query = manager.createQuery("FROM User where id =:id");
		query.setParameter("id", id);
		// this is not ideal but just a test for now
		User user = (User) query.getResultList().get(0);
		return user;
	}

	public User findByUsername(String username) {
		User user = null;
		Query  query = manager.createQuery("FROM User where userName =:username");
		query.setParameter("username", username);
		// this is not ideal but just a test for now
		if(query.getResultList().size() > 0){
			user = (User) query.getResultList().get(0);
		}
		return user;
	}
	
	@Override
	// this is how you would get list of User using EntityManager
	public List<User> getUsers(int number) {
		Query query = manager.createQuery("FROM User");
		query.setMaxResults(number);
		List<User> result = query.getResultList();
		return result;
	}

	public EntityManager getManager() {
		return manager;
	}

	public void setManager(EntityManager manager) {
		this.manager = manager;
	}
	
	
}
